package com.schezhi.link.executor.dynamic;

import org.apache.dubbo.rpc.RpcContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * @author JiaLing.Fan
 * @version 1.0
 * @date 2023/11/30 13:38
 * @description DataSourceAspect
 */

@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.hscloud.ds.executor.common.dynamic.DataSource) " +
            "|| @within(com.hscloud.ds.executor.common.dynamic.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        String dbId = RpcContext.getContext().getAttachment("dbId");
        DynamicContextHolder.push(dbId);

        try {
            return point.proceed();
        } finally {
            DynamicContextHolder.poll();
            logger.debug("clean datasource");
        }
    }
}
